using Client.Base;
using UnityEngine;
using System.Collections.Generic;
namespace Client.Hotfix
{
    [SSM(SSMWeight.SoundService)]
    public class SoundService : IAwake, IDestroy
    {
        private AudioSource AudioSource_BG;
        private AudioSource AudioSource_Effect;
        private AudioSource AudioSource_Other;
        private readonly Dictionary<string, Dictionary<string, AudioClip>> dict = new();
        private ResourceService resourceService;
        public void Awake(params object[] args)
        {
            resourceService = Api.Instance.Get<ResourceService>();

            AudioSource_BG = GameObject.Find("AudioSource_BG").GetComponent<AudioSource>();
            AudioSource_Effect = GameObject.Find("AudioSource_Effect").GetComponent<AudioSource>();
            AudioSource_Other = GameObject.Find("AudioSource_Other").GetComponent<AudioSource>();

            dict.Add("AudioSource_BG", new());
            dict.Add("AudioSource_Effect", new());
            dict.Add("AudioSource_Other", new());

            this.Log("[ Service ] - SoundService is running...");
        }

        public async void PlayEffectSound(string clipName, float volume = 1.0f)
        {
            if (!dict["AudioSource_Effect"].TryGetValue(clipName, out var clip))
            {
                clip = await resourceService.LoadSoundSync(clipName);
                dict["AudioSource_Effect"].Add(clipName, clip);
            }
            AudioSource_Effect.volume = volume;
            AudioSource_Effect.clip = clip;
            AudioSource_Effect.Play();
        }

        public async void PlayOtherSound(string clipName, float volume = 1.0f, bool loop = false)
        {
            if (!dict["AudioSource_Other"].TryGetValue(clipName, out var clip))
            {
                clip = await resourceService.LoadSoundSync(clipName);
                dict["AudioSource_Other"].Add(clipName, clip);
            }
            AudioSource_Other.loop = loop;
            AudioSource_Other.volume = volume;
            AudioSource_Other.clip = clip;
            AudioSource_Other.Play();
        }

        public async void PlayBGSound(string clipName, float volume = 1.0f, bool loop = true)
        {
            if (!dict["AudioSource_BG"].TryGetValue(clipName, out var clip))
            {
                clip = await resourceService.LoadSoundSync(clipName);
                dict["AudioSource_BG"].Add(clipName, clip);
            }
            AudioSource_BG.loop = loop;
            AudioSource_BG.volume = volume;
            AudioSource_BG.clip = clip;
            AudioSource_BG.Play();
        }

        public void Destroy()
        {
            dict.Clear();
        }
    }
}


